package com.marisfrolg.scanner.activity;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.Locale;
import java.util.Set;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnLongClick;
import com.marisfrolg.scanner.R;
import com.marisfrolg.scanner.entity.CodeMapper;
import com.marisfrolg.scanner.util.BlueToothService;
import com.marisfrolg.scanner.util.CodebarBuilder;
import com.marisfrolg.scanner.util.HadwareControll;

public class MainActivity extends Activity {
	@ViewInject(R.id.scantips)
	private TextView scantips;
	@ViewInject(R.id.oldcodevalue)
	private EditText oldcodevalue;
	@ViewInject(R.id.newcodevalue)
	private EditText newcodevalue;
	@ViewInject(R.id.btStatus)
	private TextView btStatus;
	private DbUtils db;
	public Handler sHandler = new ScanHandler(this);
	public Handler btHandler = new BTHandler(this);
	private static String dbUrl = "http://www.marisfrolg.com/dblist/code.db";

	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_WRITE = 3;
	public static final int MESSAGE_DEVICE_NAME = 4;
	public static final int MESSAGE_TOAST = 5;
	protected MediaPlayer mediaPlayer = null;
	private BlueToothService mBTService = null;
	private ArrayAdapter<String> mPairedDevicesArrayAdapter = null;// 已配对
	// private ArrayAdapter<String> mNewDevicesArrayAdapter = null;// 新搜索列表
	private Set<BluetoothDevice> devices;
	private Thread btStatus_update;
	private boolean btStatus_flag = true;
	private ProgressDialog progressDialog;
	private static final String UPDATEURL="http://www.marisfrolg.com/dblist/scannerbak.apk";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		ViewUtils.inject(this);
		HadwareControll.Open();
		HadwareControll.m_handler = sHandler;
		mBTService = new BlueToothService(this, btHandler);
		mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
				R.layout.device_name);
		refreshDB();
		scantips.setFocusable(true);
		scantips.requestFocus();
		SharedPreferences sp = this.getSharedPreferences("IP", MODE_PRIVATE);
		if (sp.getString("IP", "null").equals("null")) {
			Editor editor = sp.edit();
			editor.putString("IP", dbUrl);
			editor.commit();
		}
		
		btStatus_update = new Thread() {
			public void run() {
				while (btStatus_flag) {
					try {
						Thread.sleep(200);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					btStatus.post(new Runnable() {
						@Override
						public void run() {
							if (mBTService != null) {
								if (mBTService.getState() == BlueToothService.STATE_CONNECTED) {
									btStatus.setText(MainActivity.this
											.getResources().getString(
													R.string.str_connected));
								} else if (mBTService.getState() == BlueToothService.STATE_CONNECTING) {
									btStatus.setText(MainActivity.this
											.getResources().getString(
													R.string.str_connecting));
								} else {
									btStatus.setText(MainActivity.this
											.getResources().getString(
													R.string.str_disconnected));
								}
							}
						}
					});
				}
			}
		};
		btStatus_update.start();
	}

//	@OnClick(R.id.scantips)
//	public void toCameraScan(View v){
//		Intent in=new Intent();
//		in.setClass(this, CaptureActivity.class);
//	}
	private void refreshDB() {
		if (db != null) {
			db = null;
		}
		db = DbUtils.create(this, Environment.getExternalStorageDirectory()
				.getPath() + "/code/", "code.db");
	}

	public void play_sound() {
		try {
			if (mediaPlayer == null)
				mediaPlayer = MediaPlayer.create(this, R.raw.beep);
			mediaPlayer.stop();
			mediaPlayer.prepare();
			mediaPlayer.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@OnClick(R.id.scantips)
	public void toCameraScan(View v) {
		Intent in=new Intent();
		in.setClass(this, CaptureActivity.class);
		startActivityForResult(in, 1000);
	}
	
	
	@OnClick(R.id.printButton)
	public void onclickPrint(View v) {
		if (mBTService.getState() != BlueToothService.STATE_CONNECTED) {
			Toast.makeText(this,
					this.getResources().getString(R.string.str_unconnected),
					Toast.LENGTH_SHORT).show();
			return;
		}
		String message = newcodevalue.getText() + "";
		message=message.toUpperCase(Locale.US);
		if (message.getBytes().length > message.length()) {
			Toast.makeText(
					this,
					this.getResources().getString(R.string.str_cannotcreatebar),
					Toast.LENGTH_SHORT).show();
			return;
		}
		Bitmap btMap = null;
		SharedPreferences sp = MainActivity.this
				.getSharedPreferences("IP", MODE_PRIVATE);
		int goNum=Integer.valueOf(sp.getString("GO", "7"));
		if (message.length() > 0) {
			//btMap = CodebarBuilder.creatBarcode(this, message, 384, 120, true,
					//1);// 最后一位参数是条码格式
			btMap = CodebarBuilder.creatBarcode(this, message, 320, 125, true,
					1);// 最后一位参数是条码格式
			// iv.setImageBitmap(btMap);
		}
		if (btMap != null) {
			Bitmap bitmapOrg = btMap;// BitmapFactory.decodeFile(picPath);
			int w = bitmapOrg.getWidth();
			int h = bitmapOrg.getHeight();
			// /------
//            try {
//				mBTService.PrintImage(resizeImage(CodebarBuilder.createOneQRCode(message, 500, 200),500,200));
//			} catch (Exception e) {
//				e.printStackTrace();
//			}
			 //mBTService.PrintImage(resizeImage(bitmapOrg, w, h));
			if(goNum>255){
				goNum=7;
			}
			mBTService.PrintImage(bitmapOrg,(byte)goNum);
			// ///---------
//			String go = "\n\n";
//			try{
//				StringBuffer sb=new StringBuffer();
//				for(int i=0;i<Integer.valueOf(goNum);i++){
//					sb.append("\n");
//				}
//				go=sb.toString();
//			}catch(Exception e){
//				e.printStackTrace();
//			}
			byte[] bt = new byte[3];
			bt[0] = 27;
			bt[1] = 56;
			bt[2] = 2;// 1,2//设置字体大小
			mBTService.write(bt);
			//mBTService.PrintCharacters(go);
			return;
		}
	}

	@OnLongClick(R.id.oldcodetitle)
	public void changeClick(View v) {
		Message msg = new Message();
		msg.what = HadwareControll.BARCODE_READ;
		msg.obj = oldcodevalue.getText() + "";
		sHandler.sendMessage(msg);
	}

	@OnClick(R.id.setting)
	public void onclickSetting(View v) {
		openOptionsMenu();
	}
	@OnLongClick(R.id.setting)
	public void updateApp(View v){
		new AlertDialog.Builder(this)
		.setTitle("更新程序")
		.setMessage("将下载最新程序并更新").setPositiveButton("确定", new OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				HttpUtils http = new HttpUtils();
				http.download(UPDATEURL, Environment.getExternalStorageDirectory().getPath()+ "/code/" + "scannerbak.apk", false, false,
						new UpdateCallBack(MainActivity.this));
			}
		}).setNegativeButton("取消", null).show();
		
	}

	@Override
	protected void onDestroy() {
		HadwareControll.Close();
		HadwareControll.m_handler = null;
		btClose();
		super.onDestroy();
	}

	private void btClose() {
		if (btStatus_update != null) {
			btStatus_flag = false;
			btStatus_update = null;
		}
		try {
			Thread.sleep(200);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		if (mBTService != null) {
			mBTService.DisConnected();
			mBTService = null;
		}
		try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	// --------------- 扫描部分相关 start---------------//
	private static class ScanHandler extends Handler {
		WeakReference<MainActivity> wactivity;

		ScanHandler(MainActivity activity) {
			wactivity = new WeakReference<MainActivity>(activity);
		}

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HadwareControll.BARCODE_READ: {
				MainActivity activity = wactivity.get();
				String old = msg.obj + "";
				// String old=activity.oldcodeedit.getText().toString().trim();
				CodeMapper cm = new CodeMapper();
				cm.setOldcode(old.length()>10?old.substring(0, old.length()-4).toUpperCase(Locale.US):old.toUpperCase(Locale.US));
				try {
					CodeMapper cm1 = activity.db.findFirst(cm);
					String newcode = "";
					if (cm1 == null) {
						cm.setOldcode(old.length()>4?old.substring(0,4).toUpperCase(Locale.US):old.toUpperCase(Locale.US));
						cm1 = activity.db.findFirst(cm);
						//CodeMapperBak cmb1 = activity.db.findFirst(Selector.from(CodeMapperBak.class).where(WhereBuilder.b("oldcode", "=", cmb.getOldcode())));
						if(cm1==null){
							newcode = "没有查到该编码!";
						}else{
							newcode = cm1.getNewcode();
						}
					} else {
						newcode = cm1.getNewcode();
					}
					activity.oldcodevalue.setText(old);
					activity.newcodevalue.setText(newcode);
				} catch (Exception e) {
					e.printStackTrace();
				}
				activity.play_sound();
				break;
			}
			default:
				break;
			}
		}
	};

	// 扫描头调用
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10
				|| keyCode == KeyEvent.KEYCODE_F11) {
			HadwareControll.scan_start();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	public boolean onKeyUp(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_F9 || keyCode == KeyEvent.KEYCODE_F10
				|| keyCode == KeyEvent.KEYCODE_F11) {
			HadwareControll.scan_stop();
			return true;
		}
		return super.onKeyUp(keyCode, event);
	}

	// --------------- 扫描部分相关 end---------------//
	// --------------- 蓝牙部分相关 start---------------//

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(Menu.NONE, Menu.FIRST + 1, 1, "打开蓝牙");
		menu.add(Menu.NONE, Menu.FIRST + 2, 2, "重启蓝牙");
		// menu.add(Menu.NONE, Menu.FIRST + 3, 3, "扫描设备");
		menu.add(Menu.NONE, Menu.FIRST + 4, 4, "查看配对设备");
		menu.add(Menu.NONE, Menu.FIRST + 5, 5, "更新数据");
		menu.add(Menu.NONE, Menu.FIRST + 6, 6, "设置行距");
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		SharedPreferences sp = MainActivity.this.getSharedPreferences("IP",
				MODE_PRIVATE);
		int item_id = item.getItemId();
		switch (item_id) {
		case 2:// 打开蓝牙
			mBTService.OpenDevice();
			break;
		case 3:// 重启蓝牙
			if (mBTService.getState() == BlueToothService.STATE_CONNECTED) {
				mBTService.DisConnected();
			}
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			mBTService.CloseDevice();
			try {
				Thread.sleep(200);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			mBTService.OpenDevice();
			break;
		// case 4:// 扫描设备
		// if (!mBTService.IsOpen()) {// 判断蓝牙是否打开
		// mBTService.OpenDevice();
		// break;
		// }
		// if (mBTService.GetScanState() == BlueToothService.STATE_SCANING)
		// break;
		// // TO DO 界面弹出扫描的蓝牙设备
		// mNewDevicesArrayAdapter.clear();
		// devices = mBTService.GetBondedDevice();
		// if (devices.size() > 0) {
		// for (BluetoothDevice device : devices) {
		// mNewDevicesArrayAdapter.add(device.getName() + "\n"
		// + device.getAddress());
		// }
		// }
		// deviceList.setAdapter(mNewDevicesArrayAdapter);
		// new Thread() {
		// public void run() {
		// mBTService.ScanDevice();
		// }
		// }.start();
		// break;
		case 5:// 查看配对设备
			if (!mBTService.IsOpen()) {
				mBTService.OpenDevice();
				break;
			}
			// 创建dialog,listview 布局
			LinearLayout linearLayoutMain = new LinearLayout(this);// 自定义一个布局文件
			linearLayoutMain.setLayoutParams(new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			ListView deviceList = new ListView(this);// this为获取当前的上下文
			deviceList.setLayoutParams(new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			deviceList.setFadingEdgeLength(0);
			deviceList.setAdapter(mPairedDevicesArrayAdapter);
			linearLayoutMain.addView(deviceList);
			// 显示dialog
			final AlertDialog dialog = new AlertDialog.Builder(this)
					.setTitle("选择配对设备")
					.setView(linearLayoutMain)
					// 在这里把写好的这个listview的布局加载dialog中
					.setNegativeButton("取消",
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int which) {
									dialog.cancel();
								}
							}).create();
			dialog.setCanceledOnTouchOutside(false);// 使除了dialog以外的地方不能被点击
			dialog.show();
			// listview监听
			deviceList.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// 获取蓝牙物理地址
					if (!mBTService.IsOpen()) {// 判断蓝牙是否打开
						mBTService.OpenDevice();
						return;
					}
					if (mBTService.GetScanState() == BlueToothService.STATE_SCANING) {
						Message msg = new Message();
						msg.what = 2;
						// handler.sendMessage(msg);
						Toast.makeText(MainActivity.this, "正在扫描蓝牙设备...",
								Toast.LENGTH_SHORT).show();
					}
					if (mBTService.getState() == BlueToothService.STATE_CONNECTING) {
						return;
					}
					String info = ((TextView) view).getText().toString();
					String address = info.substring(info.length() - 17);
					mBTService.DisConnected();
					mBTService.ConnectToDevice(address);// 连接蓝牙
					dialog.cancel();
				}
			});
			mPairedDevicesArrayAdapter.clear();
			devices = mBTService.GetBondedDevice();
			if (devices.size() > 0) {
				for (BluetoothDevice device : devices) {
					mPairedDevicesArrayAdapter.add(device.getName() + "\n"
							+ device.getAddress());
				}
			} else {
				String noDevices = MainActivity.this.getResources().getString(
						R.string.str_nomatched);
				mPairedDevicesArrayAdapter.add(noDevices);
			}
			break;
		case 6:// 设置下载地址
			final EditText ip = new EditText(this);
			final TextView ipTitle = new TextView(this);
			LinearLayout downLinearLayout = new LinearLayout(this);// 自定义一个布局文件
			downLinearLayout.setLayoutParams(new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			downLinearLayout.addView(ip);
			downLinearLayout.addView(ipTitle);
			ip.setVisibility(View.INVISIBLE);
			String url = sp.getString("IP", "无");
			final String editUrl = url;
			ipTitle.setText("当前地址:(" + url + ")");
			ipTitle.setOnLongClickListener(new OnLongClickListener() {
				public boolean onLongClick(View v) {
					ipTitle.setVisibility(View.INVISIBLE);
					ip.setText(editUrl);
					ip.setVisibility(View.VISIBLE);
					return false;
				}
			});
			new AlertDialog.Builder(this).setTitle("设置更新数据地址")
					.setView(downLinearLayout)
					.setPositiveButton("确定", new OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							SharedPreferences sp = MainActivity.this
									.getSharedPreferences("IP", MODE_PRIVATE);
							if (!"".equals(ip.getText().toString().trim())) {
								Editor editor = sp.edit();
								editor.putString("IP", ip.getText().toString());
								editor.commit();
							}
							String url = sp.getString("IP", dbUrl);
							HttpUtils http = new HttpUtils();
							http.download(url, Environment.getExternalStorageDirectory().getPath()+ "/code/" + "codebak.db", false, false,
									new dbFileCallBack(MainActivity.this));
						}
					}).setNegativeButton("取消", null).show();
			break;
		case 7:// 设置行距
			String goNum=sp.getString("GO", "7");
			final EditText go = new EditText(this);
			go.setText(goNum);
			go.setLayoutParams(new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			LinearLayout goLinearLayout = new LinearLayout(this);// 自定义一个布局文件
			goLinearLayout.setLayoutParams(new LayoutParams(
					LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			goLinearLayout.addView(go);
			new AlertDialog.Builder(this).setTitle("设置行距").setView(goLinearLayout)
			.setPositiveButton("确定", new OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					SharedPreferences sp = MainActivity.this
							.getSharedPreferences("IP", MODE_PRIVATE);
					if (!"".equals(go.getText().toString().trim())) {
						Editor editor = sp.edit();
						editor.putString("GO", go.getText().toString());
						editor.commit();
					}
				}
			}).setNegativeButton("取消", null).show();
			break;
		default:
			break;
		}
		return true;
	}

	public static Bitmap resizeImage(Bitmap bitmap, int w, int h) {
		Bitmap BitmapOrg = bitmap;
		int width = BitmapOrg.getWidth();
		int height = BitmapOrg.getHeight();
		int newWidth = w;
		int newHeight = h;

		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;
		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);
		Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, w,h, matrix, true);
		return resizedBitmap;
	}

	// --------------- 蓝牙部分相关 end---------------//
	private static class BTHandler extends Handler {
		WeakReference<MainActivity> wactivity;

		BTHandler(MainActivity activity) {
			wactivity = new WeakReference<MainActivity>(activity);
		}

		public void handleMessage(Message msg) {
			MainActivity activity = wactivity.get();
			super.handleMessage(msg);
			switch (msg.what) {
			case MESSAGE_STATE_CHANGE:// 蓝牙连接状态
				switch (msg.arg1) {
				case BlueToothService.STATE_CONNECTED:// 已经连接
					break;
				case BlueToothService.STATE_CONNECTING:// 正在连接
					break;
				case BlueToothService.STATE_LISTEN:
				case BlueToothService.STATE_NONE:
					break;
				case BlueToothService.SUCCESS_CONNECT:
					Toast.makeText(
							activity,
							activity.getResources().getString(
									R.string.str_succonnect),
							Toast.LENGTH_SHORT).show();
					break;
				case BlueToothService.FAILED_CONNECT:
					Toast.makeText(
							activity,
							activity.getResources().getString(
									R.string.str_faileconnect),
							Toast.LENGTH_SHORT).show();
					break;
				case BlueToothService.LOSE_CONNECT:
					Toast.makeText(
							activity,
							activity.getResources()
									.getString(R.string.str_lose),
							Toast.LENGTH_SHORT).show();
					break;
				}
				break;
			case MESSAGE_READ:
				// sendFlag = false;//缓冲区已满
				break;
			case MESSAGE_WRITE:// 缓冲区未满
				// sendFlag = true;
				break;

			}
		}
	};

	public void onBackPressed() {
		btClose();
		System.exit(0);
	}

	private class dbFileCallBack extends RequestCallBack<File> {
		MainActivity activity;

		dbFileCallBack(MainActivity activity) {
			this.activity = (new WeakReference<MainActivity>(activity)).get();
		}

		@Override
		public void onStart() {
			progressDialog = ProgressDialog.show(activity, "正在下载", "请稍候...",
					true, false);
			super.onStart();
		}

		@Override
		public void onFailure(HttpException arg0, String arg1) {
			Toast.makeText(activity, "下载失败", Toast.LENGTH_SHORT).show();
			refreshDB();
			progressDialog.dismiss();
		}

		@Override
		public void onSuccess(ResponseInfo<File> arg0) {
			Toast.makeText(activity, "下载成功", Toast.LENGTH_SHORT).show();
			File oldFile = new File(Environment.getExternalStorageDirectory()
					.getPath() + "/code/code.db");
			File downFile = new File(Environment.getExternalStorageDirectory()
					.getPath() + "/code/codebak.db");
			oldFile.delete();
			downFile.renameTo(new File(Environment
					.getExternalStorageDirectory().getPath() + "/code/code.db"));
			refreshDB();
			progressDialog.dismiss();
		}

	}
	
	private class UpdateCallBack extends RequestCallBack<File> {
		MainActivity activity;

		UpdateCallBack(MainActivity activity) {
			this.activity = (new WeakReference<MainActivity>(activity)).get();
		}

		@Override
		public void onStart() {
			progressDialog = ProgressDialog.show(activity, "正在下载", "请稍候...",
					true, true);
			super.onStart();
		}

		@Override
		public void onFailure(HttpException arg0, String arg1) {
			Toast.makeText(activity, "下载失败", Toast.LENGTH_SHORT).show();
			progressDialog.dismiss();
		}
		
		@Override
		public void onSuccess(ResponseInfo<File> arg0) {
			File oldFile = new File(Environment.getExternalStorageDirectory().getPath() + "/code/scanner.apk");
			File downFile = new File(Environment.getExternalStorageDirectory().getPath() + "/code/scannerbak.apk");
			if(oldFile.exists()){
				oldFile.delete();
			}
			downFile.renameTo(new File(Environment.getExternalStorageDirectory().getPath() + "/code/scanner.apk"));
			progressDialog.dismiss();
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
	        intent.setDataAndType(Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath() + "/code/scanner.apk")), "application/vnd.android.package-archive");
	        activity.startActivity(intent);
		}

	}
	
	
	/***
	 * 想要获取后边的activity中返回的内容就要重写该方法 该方法将会在后边的activity调用setResult方法后被触发。
	 * requestCode 请求码
	 * 即我们在startActivityForResult中指定的那个1，我们可以通过这个标识判断，后边activity返回的是不是我们请求的东西
	 * resultCode 返回的结果码 	后边的activity给我们的一个标识状态信息的值
	 * data 返回的intent对象
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (resultCode) {
		case RESULT_OK:
			Bundle bundle = data.getExtras();
			String code = bundle.getString("code");
			Message msg=new Message();
			msg.what=HadwareControll.BARCODE_READ;
			msg.obj=code;
			sHandler.dispatchMessage(msg);
			break;

		default:
			break;
		}
	}
}
